var $ = window.$;
var event = require('../../core/event');
var jade = require('jade');

var _tmpl = jade.compileFile('./tmpl/review/item.jade');

var ret = {
	/**
	 * ui初始化，缓存界面元素，绑定事件
	 */
	init: function(){
		var self = this;
		this.focus = false;

		this.parent = $('#tool_review');
		this.parent.on('mousedown', 'li', function(e){
			var target = $(this);
			var idx = target.index();
			if(!self.focus){
				self.focus = true;
				event.trigger(event.events.global.blur, null, self);
			}
			if(target.hasClass('tool')) {
				self.addReview();
			}else{
				if(e.which == 3){
					self.manager._remove(idx);
					target.remove();
					return;
				}
				var review = self.manager._getReview(idx);
				if(!review){
					return;
				}
				self.addReview({
					idx: idx,
					param: review
				});
				if(review.note){
					event.trigger(event.events.grid.focus, review.note);
				}
			}
		});
		event.bind(event.events.global.blur, 'layer', this);
	},

	setManager: function(ma){
		this.manager = ma;
	},

	onEvent: function(e, param){
		if(e == event.events.global.blur){
			if(this.focus){
				this.focus = false;
			}
		}
	},

	sync: function() {
		var list = this.manager._getReviews();
		var html = [];
		if(list){
			for(var i=0;i<list.length;i++){
				var val = list[i];
				html.push(_tmpl(val));
			}
		}
		html.push('<li class="tool"><i></i></li>');
		this.parent.html(html);
	},

	clear: function () {
		this.parent.html('');
	},

	addReview: function(param) {
		var dialog = require('./dialog');
		dialog.setManager(this);
		dialog.init();
		dialog.show(param);
	},

	_onDialogResult: function(param) {
		if(param.idx >= 0){
			//编辑
			this.manager._change(param);
			var html = _tmpl(param.param);
			this.parent.find('li').eq(param.idx).replaceWith(html);
		}else{
			//新增
			this.manager._add(param.param);
			var html = _tmpl(param.param);
			this.parent.find('li.tool').before(html);
		}
	}
};

module.exports = ret;